using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.Text.RegularExpressions;
using TaskStatus = DocumentCreationSystem.Models.TaskStatus;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 智能任务分解器 - Agent创作应用的核心组件
    /// 能够将复杂的创作任务自动分解为可执行的子任务
    /// </summary>
    public interface IIntelligentTaskDecomposer
    {
        Task<TaskDecompositionResult> DecomposeTaskAsync(string taskDescription, TaskContext context);
        Task<List<SubTask>> GenerateSubTasksAsync(string mainTask, int maxDepth = 3);
        Task<TaskExecutionPlan> CreateExecutionPlanAsync(List<SubTask> subTasks);
        Task<TaskDependencyGraph> AnalyzeDependenciesAsync(List<SubTask> subTasks);
        Task<TaskComplexityAnalysis> AnalyzeComplexityAsync(string taskDescription);
    }

    public class IntelligentTaskDecomposer : IIntelligentTaskDecomposer
    {
        private readonly ILogger<IntelligentTaskDecomposer> _logger;
        private readonly IAIService _aiService;
        private readonly IProjectToolsService _projectToolsService;

        public IntelligentTaskDecomposer(
            ILogger<IntelligentTaskDecomposer> logger,
            IAIService aiService,
            IProjectToolsService projectToolsService)
        {
            _logger = logger;
            _aiService = aiService;
            _projectToolsService = projectToolsService;
        }

        /// <summary>
        /// 分解复杂任务为可执行的子任务
        /// </summary>
        public async Task<TaskDecompositionResult> DecomposeTaskAsync(string taskDescription, TaskContext context)
        {
            try
            {
                _logger.LogInformation($"开始分解任务: {taskDescription}");

                // 1. 分析任务复杂度
                var complexityAnalysis = await AnalyzeComplexityAsync(taskDescription);

                // 2. 生成子任务
                var subTasks = await GenerateSubTasksAsync(taskDescription, complexityAnalysis.RecommendedDepth);

                // 3. 分析依赖关系
                var dependencyGraph = await AnalyzeDependenciesAsync(subTasks);

                // 4. 创建执行计划
                var executionPlan = await CreateExecutionPlanAsync(subTasks);

                // 5. 优化任务序列
                var optimizedPlan = await OptimizeExecutionPlanAsync(executionPlan, dependencyGraph);

                var result = new TaskDecompositionResult
                {
                    OriginalTask = taskDescription,
                    SubTasks = subTasks,
                    DependencyGraph = dependencyGraph,
                    ExecutionPlan = optimizedPlan,
                    ComplexityAnalysis = complexityAnalysis,
                    EstimatedDuration = CalculateEstimatedDuration(subTasks),
                    RecommendedResources = await RecommendResourcesAsync(subTasks)
                };

                _logger.LogInformation($"任务分解完成，生成 {subTasks.Count} 个子任务");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"任务分解失败: {taskDescription}");
                throw;
            }
        }

        /// <summary>
        /// 生成子任务
        /// </summary>
        public async Task<List<SubTask>> GenerateSubTasksAsync(string mainTask, int maxDepth = 3)
        {
            var prompt = $@"
作为一个专业的任务分解专家，请将以下复杂任务分解为具体的、可执行的子任务：

主任务：{mainTask}

请按照以下格式输出子任务：
1. [任务类型] 任务名称 - 任务描述 (预估时间: X分钟) [优先级: 高/中/低]
2. [任务类型] 任务名称 - 任务描述 (预估时间: X分钟) [优先级: 高/中/低]

任务类型包括：
- RESEARCH: 研究和信息收集
- PLANNING: 规划和设计
- CREATION: 内容创作
- REVIEW: 审查和验证
- OPTIMIZATION: 优化和改进
- INTEGRATION: 整合和组装

要求：
1. 每个子任务应该是具体的、可执行的
2. 子任务之间应该有逻辑关系
3. 考虑任务的优先级和依赖关系
4. 预估合理的执行时间
5. 最多分解到 {maxDepth} 层深度

子任务列表：";

            var response = await _aiService.GenerateTextAsync(prompt, 2000, 0.7f);
            return ParseSubTasksFromResponse(response);
        }

        /// <summary>
        /// 创建执行计划
        /// </summary>
        public async Task<TaskExecutionPlan> CreateExecutionPlanAsync(List<SubTask> subTasks)
        {
            var plan = new TaskExecutionPlan
            {
                Id = Guid.NewGuid().ToString(),
                CreatedAt = DateTime.Now,
                TotalTasks = subTasks.Count,
                EstimatedDuration = CalculateEstimatedDuration(subTasks)
            };

            // 按优先级和依赖关系排序
            var sortedTasks = SortTasksByPriorityAndDependency(subTasks);

            // 创建执行阶段
            var phases = GroupTasksIntoPhases(sortedTasks);
            plan.ExecutionPhases = phases;

            // 分配资源
            plan.ResourceAllocation = await AllocateResourcesAsync(subTasks);

            return plan;
        }

        /// <summary>
        /// 分析任务依赖关系
        /// </summary>
        public async Task<TaskDependencyGraph> AnalyzeDependenciesAsync(List<SubTask> subTasks)
        {
            var graph = new TaskDependencyGraph();

            foreach (var task in subTasks)
            {
                graph.AddNode(task);
            }

            // 使用AI分析依赖关系
            var dependencyPrompt = $@"
分析以下任务之间的依赖关系：

{string.Join("\n", subTasks.Select((t, i) => $"{i + 1}. {t.Name} - {t.Description}"))}

请指出哪些任务必须在其他任务完成后才能开始。
格式：任务A -> 任务B (表示任务B依赖于任务A)

依赖关系：";

            var dependencyResponse = await _aiService.GenerateTextAsync(dependencyPrompt, 1000, 0.3f);
            var dependencies = ParseDependenciesFromResponse(dependencyResponse, subTasks);

            foreach (var dependency in dependencies)
            {
                graph.AddEdge(dependency.FromTask, dependency.ToTask);
            }

            return graph;
        }

        /// <summary>
        /// 分析任务复杂度
        /// </summary>
        public async Task<TaskComplexityAnalysis> AnalyzeComplexityAsync(string taskDescription)
        {
            var prompt = $@"
分析以下任务的复杂度：

任务：{taskDescription}

请从以下维度评估（1-10分）：
1. 技术复杂度
2. 创意要求
3. 时间需求
4. 资源需求
5. 协调难度

并给出：
- 总体复杂度评分 (1-10)
- 推荐分解深度 (1-5)
- 关键挑战点
- 建议策略

分析结果：";

            var response = await _aiService.GenerateTextAsync(prompt, 1500, 0.5f);
            return ParseComplexityAnalysis(response);
        }

        /// <summary>
        /// 解析子任务响应
        /// </summary>
        private List<SubTask> ParseSubTasksFromResponse(string response)
        {
            var subTasks = new List<SubTask>();
            var lines = response.Split('\n', StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in lines)
            {
                var match = Regex.Match(line, @"^\d+\.\s*\[(\w+)\]\s*(.+?)\s*-\s*(.+?)\s*\(预估时间:\s*(\d+)分钟\)\s*\[优先级:\s*(\w+)\]");
                if (match.Success)
                {
                    var subTask = new SubTask
                    {
                        Id = Guid.NewGuid().ToString(),
                        Type = ParseTaskType(match.Groups[1].Value),
                        Name = match.Groups[2].Value.Trim(),
                        Description = match.Groups[3].Value.Trim(),
                        EstimatedMinutes = int.Parse(match.Groups[4].Value),
                        Priority = ParsePriority(match.Groups[5].Value),
                        Status = TaskStatus.Pending,
                        CreatedAt = DateTime.Now
                    };
                    subTasks.Add(subTask);
                }
            }

            return subTasks;
        }

        /// <summary>
        /// 解析任务类型
        /// </summary>
        private TaskType ParseTaskType(string typeString)
        {
            return typeString.ToUpper() switch
            {
                "RESEARCH" => TaskType.Research,
                "PLANNING" => TaskType.Planning,
                "CREATION" => TaskType.Creation,
                "REVIEW" => TaskType.Review,
                "OPTIMIZATION" => TaskType.Optimization,
                "INTEGRATION" => TaskType.Integration,
                _ => TaskType.Creation
            };
        }

        /// <summary>
        /// 解析优先级
        /// </summary>
        private TaskPriority ParsePriority(string priorityString)
        {
            return priorityString switch
            {
                "高" => TaskPriority.High,
                "中" => TaskPriority.Medium,
                "低" => TaskPriority.Low,
                _ => TaskPriority.Medium
            };
        }

        /// <summary>
        /// 计算预估持续时间
        /// </summary>
        private TimeSpan CalculateEstimatedDuration(List<SubTask> subTasks)
        {
            var totalMinutes = subTasks.Sum(t => t.EstimatedMinutes);
            return TimeSpan.FromMinutes(totalMinutes);
        }

        /// <summary>
        /// 按优先级和依赖关系排序任务
        /// </summary>
        private List<SubTask> SortTasksByPriorityAndDependency(List<SubTask> subTasks)
        {
            return subTasks
                .OrderBy(t => t.Priority)
                .ThenBy(t => t.Type)
                .ThenBy(t => t.CreatedAt)
                .ToList();
        }

        /// <summary>
        /// 将任务分组为执行阶段
        /// </summary>
        private List<ExecutionPhase> GroupTasksIntoPhases(List<SubTask> sortedTasks)
        {
            var phases = new List<ExecutionPhase>();
            var currentPhase = new ExecutionPhase
            {
                Id = Guid.NewGuid().ToString(),
                Name = "阶段 1",
                Tasks = new List<SubTask>()
            };

            foreach (var task in sortedTasks)
            {
                // 简单的分组逻辑：按任务类型分组
                if (currentPhase.Tasks.Any() && 
                    currentPhase.Tasks.Last().Type != task.Type)
                {
                    phases.Add(currentPhase);
                    currentPhase = new ExecutionPhase
                    {
                        Id = Guid.NewGuid().ToString(),
                        Name = $"阶段 {phases.Count + 1}",
                        Tasks = new List<SubTask>()
                    };
                }
                currentPhase.Tasks.Add(task);
            }

            if (currentPhase.Tasks.Any())
            {
                phases.Add(currentPhase);
            }

            return phases;
        }

        /// <summary>
        /// 分配资源
        /// </summary>
        private async Task<Dictionary<string, object>> AllocateResourcesAsync(List<SubTask> subTasks)
        {
            var allocation = new Dictionary<string, object>
            {
                ["ai_model_usage"] = subTasks.Count(t => t.Type == TaskType.Creation || t.Type == TaskType.Research),
                ["file_operations"] = subTasks.Count(t => t.Type == TaskType.Integration),
                ["review_cycles"] = subTasks.Count(t => t.Type == TaskType.Review),
                ["estimated_tokens"] = subTasks.Sum(t => t.EstimatedMinutes * 100) // 粗略估算
            };

            return allocation;
        }

        /// <summary>
        /// 优化执行计划
        /// </summary>
        private async Task<TaskExecutionPlan> OptimizeExecutionPlanAsync(TaskExecutionPlan plan, TaskDependencyGraph dependencyGraph)
        {
            // 基于依赖关系优化执行顺序
            var optimizedPhases = new List<ExecutionPhase>();

            foreach (var phase in plan.ExecutionPhases)
            {
                var optimizedTasks = OptimizeTaskOrder(phase.Tasks, dependencyGraph);
                optimizedPhases.Add(new ExecutionPhase
                {
                    Id = phase.Id,
                    Name = phase.Name,
                    Tasks = optimizedTasks
                });
            }

            plan.ExecutionPhases = optimizedPhases;
            return plan;
        }

        /// <summary>
        /// 优化任务顺序
        /// </summary>
        private List<SubTask> OptimizeTaskOrder(List<SubTask> tasks, TaskDependencyGraph dependencyGraph)
        {
            // 拓扑排序实现
            var result = new List<SubTask>();
            var visited = new HashSet<string>();
            var visiting = new HashSet<string>();

            foreach (var task in tasks)
            {
                if (!visited.Contains(task.Id))
                {
                    TopologicalSort(task, dependencyGraph, visited, visiting, result);
                }
            }

            return result;
        }

        /// <summary>
        /// 拓扑排序辅助方法
        /// </summary>
        private void TopologicalSort(SubTask task, TaskDependencyGraph graph, 
            HashSet<string> visited, HashSet<string> visiting, List<SubTask> result)
        {
            if (visiting.Contains(task.Id))
            {
                // 检测到循环依赖
                _logger.LogWarning($"检测到循环依赖: {task.Name}");
                return;
            }

            if (visited.Contains(task.Id))
            {
                return;
            }

            visiting.Add(task.Id);

            // 先处理依赖的任务
            var dependencies = graph.GetDependencies(task.Id);
            foreach (var dependency in dependencies)
            {
                TopologicalSort(dependency, graph, visited, visiting, result);
            }

            visiting.Remove(task.Id);
            visited.Add(task.Id);
            result.Add(task);
        }

        /// <summary>
        /// 解析依赖关系响应
        /// </summary>
        private List<TaskDependency> ParseDependenciesFromResponse(string response, List<SubTask> subTasks)
        {
            var dependencies = new List<TaskDependency>();
            var lines = response.Split('\n', StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in lines)
            {
                var match = Regex.Match(line, @"(.+?)\s*->\s*(.+)");
                if (match.Success)
                {
                    var fromTaskName = match.Groups[1].Value.Trim();
                    var toTaskName = match.Groups[2].Value.Trim();

                    var fromTask = subTasks.FirstOrDefault(t => t.Name.Contains(fromTaskName) || fromTaskName.Contains(t.Name));
                    var toTask = subTasks.FirstOrDefault(t => t.Name.Contains(toTaskName) || toTaskName.Contains(t.Name));

                    if (fromTask != null && toTask != null)
                    {
                        dependencies.Add(new TaskDependency
                        {
                            FromTask = fromTask,
                            ToTask = toTask,
                            DependencyType = DependencyType.FinishToStart
                        });
                    }
                }
            }

            return dependencies;
        }

        /// <summary>
        /// 解析复杂度分析
        /// </summary>
        private TaskComplexityAnalysis ParseComplexityAnalysis(string response)
        {
            // 简化的解析逻辑，实际应用中可以更复杂
            var analysis = new TaskComplexityAnalysis
            {
                TechnicalComplexity = ExtractScore(response, "技术复杂度"),
                CreativeRequirement = ExtractScore(response, "创意要求"),
                TimeRequirement = ExtractScore(response, "时间需求"),
                ResourceRequirement = ExtractScore(response, "资源需求"),
                CoordinationDifficulty = ExtractScore(response, "协调难度"),
                OverallComplexity = ExtractScore(response, "总体复杂度"),
                RecommendedDepth = ExtractScore(response, "推荐分解深度", 3),
                KeyChallenges = ExtractChallenges(response),
                RecommendedStrategy = ExtractStrategy(response)
            };

            return analysis;
        }

        /// <summary>
        /// 从响应中提取评分
        /// </summary>
        private int ExtractScore(string response, string dimension, int defaultValue = 5)
        {
            var pattern = $@"{dimension}[：:]\s*(\d+)";
            var match = Regex.Match(response, pattern);
            return match.Success ? int.Parse(match.Groups[1].Value) : defaultValue;
        }

        /// <summary>
        /// 提取关键挑战
        /// </summary>
        private List<string> ExtractChallenges(string response)
        {
            var challenges = new List<string>();
            var lines = response.Split('\n');
            bool inChallengeSection = false;

            foreach (var line in lines)
            {
                if (line.Contains("关键挑战") || line.Contains("挑战点"))
                {
                    inChallengeSection = true;
                    continue;
                }

                if (inChallengeSection && line.Contains("建议策略"))
                {
                    break;
                }

                if (inChallengeSection && !string.IsNullOrWhiteSpace(line))
                {
                    challenges.Add(line.Trim());
                }
            }

            return challenges;
        }

        /// <summary>
        /// 提取建议策略
        /// </summary>
        private string ExtractStrategy(string response)
        {
            var strategyIndex = response.IndexOf("建议策略");
            if (strategyIndex >= 0)
            {
                return response.Substring(strategyIndex + 4).Trim();
            }
            return "暂无特定策略建议";
        }

        /// <summary>
        /// 推荐资源
        /// </summary>
        private async Task<List<string>> RecommendResourcesAsync(List<SubTask> subTasks)
        {
            var resources = new List<string>();

            var creationTasks = subTasks.Count(t => t.Type == TaskType.Creation);
            var researchTasks = subTasks.Count(t => t.Type == TaskType.Research);
            var reviewTasks = subTasks.Count(t => t.Type == TaskType.Review);

            if (creationTasks > 0)
            {
                resources.Add($"AI创作模型 (预计使用 {creationTasks * 2000} tokens)");
            }

            if (researchTasks > 0)
            {
                resources.Add($"信息检索工具 ({researchTasks} 次查询)");
            }

            if (reviewTasks > 0)
            {
                resources.Add($"质量评估工具 ({reviewTasks} 次评估)");
            }

            return resources;
        }
    }
}
